import bcrypt from 'bcryptjs'
import { readValidatedBody } from 'h3'
import { fromError } from 'zod-validation-error'
import { eq } from 'drizzle-orm'
import { usersLoginRequestSchema, usersTable } from '~~/server/db/schema/user'
import { db } from '~~/server/db'
import { TokenService } from '~~/server/utils/tokens'

export default defineEventHandler(async (event) => {
  const validationResult = await readValidatedBody(event, (body) =>
    usersLoginRequestSchema.safeParse(body)
  )

  if (!validationResult.success) {
    throw createError({
      statusCode: 400,
      message: fromError(validationResult.error).toString()
    })
  }

  const { phone, password } = validationResult.data

  try {
    // 查找用户
    const users = await db.select().from(usersTable).where(eq(usersTable.phone, phone)).limit(1)

    const targetUser = users[0]

    if (!targetUser) {
      throw createError({
        statusCode: 401,
        message: '手机号或密码错误'
      })
    }

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, targetUser.password)
    if (!isValidPassword) {
      throw createError({
        statusCode: 401,
        message: '手机号或密码错误'
      })
    }

    // 生成 tokens
    const accessToken = TokenService.generateAccessToken({
      id: targetUser.id,
      phone: targetUser.phone,
      role: targetUser.role
    })

    const refreshToken = TokenService.generateRefreshToken({
      id: targetUser.id
    })

    // 保存 refresh token 到数据库
    await TokenService.saveRefreshToken(targetUser.id, refreshToken)

    // 设置 cookies
    setCookie(event, 'accessToken', accessToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      maxAge: 15 * 60,
      path: '/',
      sameSite: 'strict'
    })

    setCookie(event, 'refreshToken', refreshToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      maxAge: 7 * 24 * 60 * 60,
      path: '/',
      sameSite: 'strict'
    })

    return {
      message: '登录成功',
      data: {
        id: targetUser.id,
        phone: targetUser.phone,
        role: targetUser.role,
        name: targetUser.name
      }
    }
  } catch (error: any) {
    if (error.statusCode === 401) {
      throw error
    }
    console.error('Login error:', error)
    throw createError({
      statusCode: 500,
      message: '登录失败，请稍后重试'
    })
  }
})
